package com.bluesky.framework.security.config.mobile;

import com.bluesky.framework.security.service.ICustomUserDetailsService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 手机号验证码Provider
 *
 * @author Kevin
 */
@Component
public class MobileCodeAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private ICustomUserDetailsService customUserDetailsService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String mobile = authentication.getName();
        String code = authentication.getCredentials().toString();
        checkSmsCode();
        UserDetails userDetails = customUserDetailsService.loadUserByMobile(mobile);
        if (Objects.isNull(userDetails)) {
            throw new UsernameNotFoundException("user not found");
        }
        return new MobileCodeAuthenticationToken(userDetails, code, userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return MobileCodeAuthenticationToken.class.isAssignableFrom(aClass);
    }

    private void checkSmsCode() {

    }

}
